import React, { useEffect } from 'react';
import { Select } from 'antd';
import { fetchWarehouses } from '@/service/api';

interface WarehouseSelectorProps {
  onWarehouseChanged: (warehouse: Bn.Meta.MetaWarehouse) => void;
}

const WarehouseSelector = ({ onWarehouseChanged }: WarehouseSelectorProps) => {
  const [options, setOptions] = useState<{ label: string; value: string }[]>();
  const [selectValue, setSelectValue] = useState<string>();

  const handleSelect = (value: string, option: any) => {
    console.debug(`WarehouseSelector::handleChange ${value}`);
    console.debug(option);
    setSelectValue(value);
    onWarehouseChanged(option.item);
  };

  useEffect(() => {
    (async () => {
      let warehouses = (await fetchWarehouses()).data;
      if (warehouses === null) {
        warehouses = [] as Bn.Meta.MetaWarehouse[];
      }
      const _options = [] as { label: string; value: string; item: any }[];
      warehouses.forEach(ele => {
        _options.push({
          label: ele.dwName,
          value: ele.id.toString(),
          item: ele
        });
      });
      setOptions(_options);
      if (_options.length > 0) {
        setSelectValue(_options[0].value);
        onWarehouseChanged(_options[0].item);
      }
    })();
  }, []);

  return (
    <Select
      style={{ width: '100%' }}
      onSelect={handleSelect}
      value={selectValue}
      options={options}
    />
  );
};

export default WarehouseSelector;
